package com.kernelstudio.framework.compatible.supports.liquibase.database;
/*
 * This file is part of the kernelstudio package.
 *
 * (c) 2014-2024 zlin <admin@kernelstudio.com>
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

import liquibase.Scope;
import liquibase.database.DatabaseConnection;
import liquibase.database.core.MySQLDatabase;
import liquibase.exception.DatabaseException;
import liquibase.logging.Logger;

/**
 * 适配人大金仓数据库
 */
public class KingBase8MySQLDatabase extends MySQLDatabase {

    private static final Logger LOG = Scope.getCurrentScope().getLog(KingBase8MySQLDatabase.class);

    public static final String PRODUCT_NAME = "KingbaseES";

    public static final String SHORT_NAME = "kingbase8";

    private static final int DEFAULT_TCP_PORT_NUMBER = 54321;

    @Override
    public String getShortName() {
        return SHORT_NAME;
    }

    @Override
    protected String getDefaultDatabaseProductName() {
        return PRODUCT_NAME;
    }

    @Override
    public Integer getDefaultPort() {
        return DEFAULT_TCP_PORT_NUMBER;
    }

    @Override
    public String getDefaultDriver(String url) {
        if (url.startsWith("jdbc:kingbase8:")) {
            return "com.kingbase8.Driver";
        }
        return null;
    }

    @Override
    public int getPriority() {
        //提高优先级以便优先于liquibase自带的
        return PRIORITY_DATABASE;
    }

    @Override
    public boolean isCorrectDatabaseImplementation(DatabaseConnection conn) throws DatabaseException {
        if (!PRODUCT_NAME.equalsIgnoreCase(conn.getDatabaseProductName())) {
            return false;
        }
        //getDatabaseMajorVersion()返回的是12应该是Kingbase封装的postgres版本
        int majorVersion = conn.getDatabaseMajorVersion();
        int minorVersion = conn.getDatabaseMinorVersion();
        if (majorVersion < 12) {
            LOG.warning(
                    String.format(
                            "Your Kingbase8 software version (%d.%d) seems to indicate that your software is " +
                                    "older than %d.%d. This means that you might encounter strange behaviour and " +
                                    "incorrect error messages.", majorVersion, minorVersion, 12, 1));
        }
        return true;
    }

    /**
     * Should the database use "serial" datatypes vs. "generated by default as identity"
     */
    public boolean useSerialDatatypes() {
        //postgres10以上版本默认使用 "generated by default as identity"
        //如果需要使用"serial" datatypes，则都返回true
        return true;
    }
}